﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using System.Web;
using Newtonsoft.Json.Linq;
using NPOI.SS.Formula.Functions;
using NPOI.XWPF.Extractor;
using NPOI.XWPF.UserModel;
using Easy.Model;
using Easy.Operation;

namespace Easy.BLL
{
    public class ServiceViewDocumentBLL
    {
        int flag = 0;
        Dictionary<string, List<OptionSet>> leadFields = new Core("TLM_lead").GetEntityOptions();
        public MemoryStream ExportDoc(Guid id,Guid currentUserId)
        {
            
            DataService service = new DataService("TLM_service", currentUserId);
            Dictionary<string, object> ServiceInfoDic = service.Retrieve_Dic(id);
            Dictionary<string,object> ContactInfoDic=null;
            int state=-1;
            if (ServiceInfoDic["TLM_userid".ToLower()] !=null&& !String.IsNullOrWhiteSpace(ServiceInfoDic["TLM_userid".ToLower()].ToString()))
            {
                try
                {
                    JObject obj = ServiceInfoDic["TLM_userid".ToLower()] as JObject;
                    ContactInfoDic =
                        new DataService("TLM_contact", currentUserId).Retrieve_Dic(
                            new Guid(obj.GetValue("id").ToString()));
                    state = 0;
                }
                catch (Exception)
                {
                    
                }
                
            }
            else
            {
                if (ServiceInfoDic["TLM_leadid".ToLower()] != null &&
                    !String.IsNullOrWhiteSpace(ServiceInfoDic["TLM_leadid".ToLower()].ToString()))
                {
                    try
                    {
                        JObject obj = ServiceInfoDic["TLM_leadid".ToLower()] as JObject;
                        ContactInfoDic =
                            new DataService("TLM_lead", currentUserId).Retrieve_Dic(
                                new Guid(obj.GetValue("id").ToString()));
                        state = 1;
                    }
                    catch (Exception)
                    {

                    }
                }
            }
            String path = System.AppDomain.CurrentDomain.BaseDirectory + "ISV\\SendingEngineers\\Model.docx";
            MemoryStream ModelStream=new MemoryStream(File.ReadAllBytes(path));
            XWPFDocument doc = new XWPFDocument(ModelStream);
            foreach (var temp in doc.Paragraphs)
            {
                InsteadKeyWord(null,temp, ContactInfoDic, ServiceInfoDic,state);
            }
            foreach (var tables in doc.Tables)
            {
                foreach (var row in tables.Rows)
                {
                    foreach (var cell in row.GetTableCells())
                    {
                        try
                        {
                            foreach (var temp in cell.Paragraphs)
                            {
                                InsteadKeyWord(cell, temp, ContactInfoDic, ServiceInfoDic,state);
                            }
                        }
                        catch (Exception)
                        {
                        }
                        
                    }
                }
            }
            MemoryStream OutputStream=new MemoryStream();
            doc.Write(OutputStream);
            return OutputStream;
        }

        private void InsteadKeyWord(XWPFTableCell cell,XWPFParagraph temp, Dictionary<string, object> ContactInfoDic, Dictionary<string, object> ServiceInfoDic,int state=0)
        {
            if(flag>=9) return;
            try
            {
                string data;
                if (state == 0) data = ContactInfoDic["TLM_CorporateName".ToLower()].ToString();
                else
                {
                    data = ContactInfoDic["TLM_name".ToLower()].ToString();
                }
                temp.ReplaceText("{客户名称}", data);
                flag++;
            }
            catch (Exception)
            {
            }
            try
            {
                temp.ReplaceText("{编号}", ServiceInfoDic["TLM_name".ToLower()].ToString());
                flag++;
            }
            catch (Exception)
            {
            }
            try
            {
                temp.ReplaceText("{客户地址}", ServiceInfoDic["TLM_address".ToLower()].ToString());
                flag++;
            }
            catch (Exception)
            {

            }
            try
            {
                temp.ReplaceText("{联系人姓名}", ServiceInfoDic["TLM_contact".ToLower()].ToString());
                flag++;
            }
            catch (Exception)
            {
            }
            try
            {
                temp.ReplaceText("{联系人电话}", ServiceInfoDic["TLM_phone".ToLower()].ToString());
                flag++;
            }
            catch (Exception)
            {
            }
            try
            {
                temp.ReplaceText("{联系人EMAIL}", ContactInfoDic["TLM_email".ToLower()].ToString());
                flag++;
            }
            catch (Exception)
            {
            }
            try
            {
                string data;
                if (state == 0)
                {
                    data=ContactInfoDic["TLM_jobtitle".ToLower()].ToString();
                }
                else
                {
                    int i = (int)ContactInfoDic["TLM_Contact_Level".ToLower()];
                    data = "";
                    foreach (var lis in leadFields["TLM_Contact_Level".ToLower()])
                    {
                        if (lis.Value == i)
                        {
                            data = lis.Text;
                            break;
                        }
                    }
                    
                }
                temp.ReplaceText("{联系人职务}", data);
                flag++;
            }
            catch (Exception)
            {
            }
            try
            {
                temp.ReplaceText("{预计服务时间}", ServiceInfoDic["tlm_begin_time"].ToString());
                flag++;
            }
            catch (Exception)
            {
                
            }
            try
            {
                temp.ReplaceText("{服务项目}", "");
                String str = ServiceInfoDic["tlm_content"].ToString();
                var strrange = str.Split('\n');
                for (int i = 0; i < cell.Paragraphs.Count; i++)
                {
                    cell.RemoveParagraph(i);
                }
                foreach (string t in strrange)
                {
                    if(String.IsNullOrWhiteSpace(t)) continue;
                    cell.AddParagraph().CreateRun().SetText(t); 
                }

                flag++;
            }
            catch (Exception)
            {
                
            }
            //覆盖未替换字段为空
            try
            {
                temp.ReplaceText("{客户名称}", "");
                flag++;
            }
            catch (Exception)
            {
            }
            try
            {
                temp.ReplaceText("{编号}", "");
                flag++;
            }
            catch (Exception)
            {
            }
            try
            {
                temp.ReplaceText("{客户地址}", "");
                flag++;
            }
            catch (Exception)
            {

            }
            try
            {
                temp.ReplaceText("{联系人姓名}", "");
                flag++;
            }
            catch (Exception)
            {
            }
            try
            {
                temp.ReplaceText("{联系人电话}", "");
                flag++;
            }
            catch (Exception)
            {
            }
            try
            {
                temp.ReplaceText("{联系人EMAIL}", "");
                flag++;
            }
            catch (Exception)
            {
            }
            try
            {
                temp.ReplaceText("{联系人职务}", "");
                flag++;
            }
            catch (Exception)
            {
            }
            try
            {
                temp.ReplaceText("{预计服务时间}", "");
                flag++;
            }
            catch (Exception)
            {

            }
        }
    }
}